package models

import (
	"errors"
	"fmt"
	"reflect"
	"strings"
	"time"

	"gitee.com/lzqysoft/ims/libs/encrypt"
	"github.com/astaxie/beego/orm"
)

type SfTodoManager struct {
	Id       string    `orm:"column(id);pk"`
	Name     string    `orm:"column(name)"`
	Remark   string    `orm:"column(remark);null"`
	Status   int       `orm:"column(status)"`
	Isdelete int       `orm:"column(isdelete)"`
	Ctime    time.Time `orm:"column(ctime);type(timestamp with time zone)"`
	Creater  string    `orm:"column(creater);null"`
	Utime    time.Time `orm:"column(utime);type(timestamp with time zone)"`
	Type     int       `orm:"column(type);null"`
	Title    string    `orm:"column(title);null"`
	Content  string    `orm:"column(content);null"`
	RoleId   string    `orm:"column(role_id);null"`
	Finish   int       `orm:"column(finish);null"`
	BusyId   string    `orm:"column(busy_id);null"`
	BusyName string    `orm:"column(busy_name);null"`
	JyType   int       `orm:"column(jy_type);null"`
	Updater  string    `orm:"column(updater);null"`
	Finisher string    `orm:"column(finisher);null"`
}

func (t *SfTodoManager) TableName() string {
	return "sf_todo_manager"
}

func init() {
	orm.RegisterModel(new(SfTodoManager))
}

func GenerateSfTodoManager() *SfTodoManager {
	var m SfTodoManager
	m.Id = encrypt.GetGuid()
	m.Status = 1
	m.Isdelete = 0
	m.Ctime = time.Now()
	m.Utime = time.Now()
	return &m
}

// AddSfTodoManager insert a new SfTodoManager into database and returns
// last inserted Id on success.
func AddSfTodoManager(m *SfTodoManager) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetSfTodoManagerById retrieves SfTodoManager by Id. Returns error if
// Id doesn't exist
func GetSfTodoManagerById(id string) (v *SfTodoManager, err error) {
	o := orm.NewOrm()
	v = &SfTodoManager{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// GetAllSfTodoManager retrieves all SfTodoManager matches certain condition. Returns empty list if
// no records exist
func GetAllSfTodoManager(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(SfTodoManager))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		if strings.Contains(k, "isnull") {
			qs = qs.Filter(k, (v == "true" || v == "1"))
		} else {
			qs = qs.Filter(k, v)
		}
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []SfTodoManager
	qs = qs.OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

// UpdateSfTodoManager updates SfTodoManager by Id and returns error if
// the record to be updated doesn't exist
func UpdateSfTodoManagerById(m *SfTodoManager) (err error) {
	o := orm.NewOrm()
	v := SfTodoManager{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteSfTodoManager deletes SfTodoManager by Id and returns error if
// the record to be deleted doesn't exist
func DeleteSfTodoManager(id string) (err error) {
	o := orm.NewOrm()
	v := SfTodoManager{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&SfTodoManager{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

// 获取待送检待办事项
func GetDaiSongJian(user *User) ([]SfTodoUser, error) {
	o := orm.NewOrm()
	var todolist []SfTodoUser
	_, err := o.QueryTable(new(SfTodoUser)).Filter("Type", 0).Filter("UserId", user.Id).All(&todolist)
	return todolist, err
}

// 获取待取件检待办事项
func GetDaiQujian(user *User) ([]SfTodoUser, error) {
	o := orm.NewOrm()
	var todolist []SfTodoUser
	_, err := o.QueryTable(new(SfTodoUser)).Filter("Type", 1).Filter("UserId", user.Id).All(&todolist)
	return todolist, err
}

// 获取待收检待办事项
func GetDaiShouJian(user *User) ([]orm.Params, error) {
	o := orm.NewOrm()
	//var todolist []SfTodoManager
	var maps []orm.Params
	sql := `
SELECT
	t1.*,
	t2.title AS case_name,
	t2."no",
	t2.category,
	t2.appoint_user ,
	t2.dept_name
FROM
	sf_todo_manager t1
	LEFT JOIN sf_case t2 ON t1.busy_id = t2."id"
	WHERE t1."type"= ? AND t1.jy_type = ? AND t1.role_id = ? AND t1.finish = ?
`
	_, err := o.Raw(sql, 0, user.JdType, user.Role[0].Id, 0).Values(&maps)
	//_, err := o.QueryTable(new(SfTodoManager)).Filter("Type", 0).Filter("RoleId", user.Role[0].Id).
	//	Filter("JyType",user.JdType).All(&todolist)
	return maps, err
}

// 获取检验中待办事项
func GetJianYanZhong(user *User) ([]orm.Params, error) {
	o := orm.NewOrm()
	//var todolist []SfTodoManager
	var maps []orm.Params
	sql := `
SELECT
	t1.*,
	t2.title AS case_name,
	t2."no",
	t2.category,
	t2.appoint_user ,
	t2.dept_name,
	t2.lock
FROM
	sf_todo_manager t1
	LEFT JOIN sf_case t2 ON t1.busy_id = t2."id"
	WHERE t1."type"= ? AND t1.jy_type = ? AND t1.role_id = ? AND t1.finish = ?
`
	_, err := o.Raw(sql, 1, user.JdType, user.Role[0].Id, 0).Values(&maps)
	//_, err := o.QueryTable(new(SfTodoManager)).Filter("Type", 0).Filter("RoleId", user.Role[0].Id).
	//	Filter("JyType",user.JdType).All(&todolist)
	return maps, err
}

// 获取鉴定中待办事项
func GetJianDingZhong(user *User) ([]orm.Params, error) {
	o := orm.NewOrm()
	//var todolist []SfTodoManager
	var maps []orm.Params
	sql := `
SELECT
	t1.*,
	t2.title AS case_name,
	t2."no",
	t2.category,
	t2.appoint_user ,
	t2.dept_name,
	t2.lock
FROM
	sf_todo_manager t1
	LEFT JOIN sf_case t2 ON t1.busy_id = t2."id"
	WHERE t1."type"= ? AND t1.jy_type = ? AND t1.role_id = ? AND t1.finish = ?
`
	_, err := o.Raw(sql, 2, user.JdType, user.Role[0].Id, 0).Values(&maps)
	//_, err := o.QueryTable(new(SfTodoManager)).Filter("Type", 0).Filter("RoleId", user.Role[0].Id).
	//	Filter("JyType",user.JdType).All(&todolist)
	return maps, err
}

// 获取取件待办事项
func GetDaiQuJian(user *User) ([]orm.Params, error) {
	o := orm.NewOrm()
	//var todolist []SfTodoManager
	var maps []orm.Params
	sql := `
SELECT
	t1.*,
	t2.title AS case_name,
	t2."no",
	t2.category,
	t2.appoint_user ,
	t2.dept_name
FROM
	sf_todo_manager t1
	LEFT JOIN sf_case t2 ON t1.busy_id = t2."id"
	WHERE t1."type"= ? AND t1.jy_type = ? AND t1.role_id = ? AND t1.finish = ?
`
	_, err := o.Raw(sql, 3, user.JdType, user.Role[0].Id, 0).Values(&maps)
	//_, err := o.QueryTable(new(SfTodoManager)).Filter("Type", 0).Filter("RoleId", user.Role[0].Id).
	//	Filter("JyType",user.JdType).All(&todolist)
	return maps, err
}

// 获取已取件待办事项
func GetYiQuJian(user *User) ([]orm.Params, error) {
	o := orm.NewOrm()
	//var todolist []SfTodoManager
	var maps []orm.Params
	// 	sql := `
	// SELECT
	// 	t1.*,
	// 	t2.title AS case_name,
	// 	t2."no",
	// 	t2.category,
	// 	t2.appoint_user ,
	// 	t2.dept_name
	// FROM
	// 	sf_todo_manager t1
	// 	LEFT JOIN sf_case t2 ON t1.busy_id = t2."id"
	// 	WHERE t1."type"= ? AND t1.jy_type = ? AND t1.role_id = ?
	// `
	sql := `
	SELECT 
		t1.*,
		t2.title AS case_name,
		t2."no",
		t2.category,
		t2.appoint_user ,
		t2.dept_name,
		t3.rate,
		t3."content" as "evaluation"
	FROM sf_todo_manager t1 
	RIGHT JOIN sf_case t2 ON t1.busy_id = t2."id"
	RIGHT JOIN sf_rate t3 ON t1.id = t3.todo_id
	WHERE t1."type"= ? AND t1.jy_type = ? AND t1.role_id = ?`
	_, err := o.Raw(sql, 4, user.JdType, user.Role[0].Id).Values(&maps)
	//_, err := o.QueryTable(new(SfTodoManager)).Filter("Type", 0).Filter("RoleId", user.Role[0].Id).
	//	Filter("JyType",user.JdType).All(&todolist)
	return maps, err
}

func GetSfTodoManagerByBusy(busyId string) ([]SfTodoManager, error) {
	o := orm.NewOrm()
	var array []SfTodoManager
	_, err := o.QueryTable(new(SfTodoManager)).Filter("BusyId", busyId).All(&array)
	return array, err
}
